package com.ccl.iot;


import android.app.ActivityManager;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Looper;
import android.support.multidex.MultiDexApplication;
import android.util.Log;

import com.ccl.iot.bean.BatchBeanDao;
import com.ccl.iot.bean.DaoMaster;
import com.ccl.iot.bean.DaoSession;
import com.ccl.iot.bean.IOTHuiJuBeanDao;
import com.ccl.iot.dvr.utils.LogUtil;
import com.ccl.iot.huiju.MainActivity;
import com.ccl.iot.huiju.db.Helper;
import com.ccl.iot.managers.MainManager;
import com.ccl.iot.monitor.NetworkMonitor;
import com.ccl.iot.privates.BitmapCollector;
import com.ccl.iot.publics.Messager;
import com.ccl.iot.updater.AppUpdater;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.List;

public class App extends MultiDexApplication {

    private static App gInstance = null;

    private boolean iInited = false;

    private static Handler mHandler;
    private static Thread mMainThread;
    private static long mMainThreadId;
    private static Looper mMainThreadLooper;


    private static DaoSession daoSession;


    private boolean isRunningAsLocal() {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        int largeMemoryClass = activityManager.getLargeMemoryClass();
        int memoryClass = activityManager.getMemoryClass();
        LogUtil.e(MainActivity.TAG,"--------------largeMemoryClass:" + largeMemoryClass + "--memoryClass:" + memoryClass);

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();

        for (ActivityManager.RunningAppProcessInfo processInfo : appProcesses) {
            if (processInfo != null && processInfo.pid == pid) {
                return processInfo.processName.equals(this.getPackageName());
            }
        }

        return false;
    }

    private void AppTest() {
    }

    @Override
    public void onCreate() {
        //=========================bugly start=====================
        CrashReport.initCrashReport(getApplicationContext(), "40074ddd22", true);
        //=========================bugly end=====================

        Log.d(App.class.getName(), "Application creating...");

        super.onCreate();

        gInstance = this;

        // handler,用来子线程和主线程通讯
        mHandler = new Handler();

        // 主线程
        mMainThread = Thread.currentThread();
        // id
        // mMainThreadId = mMainThread.getId();
        mMainThreadId = android.os.Process.myTid();

        // looper
        mMainThreadLooper = getMainLooper();

        AppTest();

        if (isRunningAsLocal()) {
            initialize();
        }


        setupDatabase();


    }

    @Override
    public void onTerminate() {
        super.onTerminate();

        gInstance = null;

        Log.d(App.class.getName(), "Application terminated!");
    }

    public static App GetInstance() {
        return gInstance;
    }

    public void initialize() {
        AppUpdater.Initialize(this);

        if (iInited == false) {
            if (MainManager.Prepare()) {
                iInited = true;

                Messager.Initialize(this);

                NetworkMonitor.Initialize(this);

                MainManager.GetDefaultManager(this);


            } else {
                Log.w(App.class.getName(), "System not ready");
            }
        }
    }


    @Override
    public void onLowMemory() {
        super.onLowMemory();

        Log.w("App", "onLowMemory");

        BitmapCollector.Clear();

    }

//    @SuppressLint("NewApi")
//    @Override
//    public void onTrimMemory(int level) {
//        super.onTrimMemory(level);
//
//        Log.w("App", "onTrimMemory level:  " + level);
//    }

    public static Context getContext() {
        return gInstance;
    }

    public static Handler getHandler() {
        return mHandler;
    }

    public static Thread getMainThread() {
        return mMainThread;
    }

    public static long getMainThreadId() {
        return mMainThreadId;
    }



    /**
     * 配置数据库
     */
    private void setupDatabase() {

        try {
            Helper monitorHelper = new Helper(this);
            SQLiteDatabase db = monitorHelper.getWritableDatabase();
            // 注意：该数据库连接属于 DaoMaster，所以多个 Session 指的是相同的数据库连接。
            DaoMaster daoMaster = new DaoMaster(db);
            daoSession = daoMaster.newSession();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static IOTHuiJuBeanDao getIOTHuiJuBeanDao() {
        return daoSession.getIOTHuiJuBeanDao();
    }

    public static BatchBeanDao getBatchBeanDao() {
        return daoSession.getBatchBeanDao();
    }

}
